package top.lcm889.oj.leetcodeTop200;

import top.lcm889.oj.databean.TreeNode;

import java.util.*;

/**
 * @author Coder-lcm
 * @date 2021/4/10
 */
public class LC102_二叉树的层序遍历 {
    // BFS快速结束战斗
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        List<List<Integer>> res = new ArrayList<>();
        while(!queue.isEmpty()){
            int size = queue.size();
            LinkedList<Integer> cur = new LinkedList();
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(cur);
        }
        return res;

    }

    public static void main(String[] args) {
        LC102_二叉树的层序遍历 test = new LC102_二叉树的层序遍历();
        TreeNode root = new TreeNode(23);
        TreeNode left = new TreeNode(32);
        TreeNode right = new TreeNode(12);
        root.left = left;
        root.right = right;
        List<List<Integer>> res = test.levelOrder(root);
        res.forEach(each-> {
            each.forEach(e -> {
                System.out.print(e + ", ");
            });
            System.out.println();
        });
    }
}
